package tags;

import dao.DAOFactory;
import dao.IAirportDAO;
import dao.tro.Flight;
import dao.tro.FlightComparatorTimeDesc;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class MainFlightTag extends TagSupport {
    private int flightCount;

    @Override
    public int doStartTag() throws JspException {
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        IAirportDAO factory =  DAOFactory.getDAOFactory(1).getAirportDAO();
        ArrayList<Flight> flightList = (ArrayList<Flight>) DAOFactory.getDAOFactory(1).getFlightDAO().flightList(flightCount);
        Collections.sort(flightList, new FlightComparatorTimeDesc());
        try {
            for (Flight flight: flightList) {
                flight.setDepartureAirport(factory.loadCountryName(flight.getDepartureAirport()));
                flight.setDestinationAirport(factory.loadCountryName(flight.getDestinationAirport()));
                pageContext.setAttribute("singleFlight", flight, PageContext.REQUEST_SCOPE);
                pageContext.include("../Templates/Flight.jsp");
            }
        } catch (ServletException|IOException e) {
            throw new JspException();
        }
        return EVAL_PAGE;
    }

    public int getFlightCount() {
        return flightCount;
    }

    public void setFlightCount(int flightCount) {
        this.flightCount = flightCount;
    }
}
